package com.ruoyi.web.controller.pinko;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.PinkoTransaction;
import com.ruoyi.system.service.IPinkoTransactionService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * Pinko交易Controller
 * 
 * @author ruoyi
 * @date 2024-06-07
 */
@RestController
@RequestMapping("/system/transaction")
public class PinkoTransactionController extends BaseController
{
    @Autowired
    private IPinkoTransactionService pinkoTransactionService;

    /**
     * 查询Pinko交易列表
     */
    @PreAuthorize("@ss.hasPermi('system:transaction:list')")
    @GetMapping("/list")
    public TableDataInfo list(PinkoTransaction pinkoTransaction)
    {
        startPage();
        List<PinkoTransaction> list = pinkoTransactionService.selectPinkoTransactionList(pinkoTransaction);
        return getDataTable(list);
    }
    @ApiOperation("最新10条交易数据")
    @GetMapping("last10list")
    @Operation(summary = "最新10条交易数据")
    @Anonymous
    public AjaxResult last10list(){
        startPage();
        List<PinkoTransaction> list = pinkoTransactionService.selectPinkoTransactionList(null);
       /* for (var item: list
        ) {
            String currencyType = item.getCurrency();
            BigInteger SATOSHISCOIN = new BigInteger("100000000");
            switch (currencyType) {
                case "ETH":
                    SATOSHISCOIN = new BigInteger("1000000000000000000");
                    break;
                case "BTC":
                    SATOSHISCOIN = new BigInteger("100000000");
                    break;
                case "TRON":
                    SATOSHISCOIN = new BigInteger("1000000");
                    break;
            }
            BigDecimal TRONC = new BigDecimal(item.getValue()).divide(new BigDecimal(SATOSHISCOIN));
            item.setValue(TRONC.longValue());
        }*/
        return success(list);
    }
    /**
     * 导出Pinko交易列表
     */
    @PreAuthorize("@ss.hasPermi('system:transaction:export')")
    @Log(title = "Pinko交易", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PinkoTransaction pinkoTransaction)
    {
        List<PinkoTransaction> list = pinkoTransactionService.selectPinkoTransactionList(pinkoTransaction);
        ExcelUtil<PinkoTransaction> util = new ExcelUtil<PinkoTransaction>(PinkoTransaction.class);
        util.exportExcel(response, list, "Pinko交易数据");
    }

    /**
     * 获取Pinko交易详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:transaction:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pinkoTransactionService.selectPinkoTransactionById(id));
    }

    /**
     * 新增Pinko交易
     */
    @Log(title = "Pinko交易", businessType = BusinessType.INSERT)
    @ApiOperation("保存交易,只保存transaction字段，其他字段为介绍")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "transaction", value = "交易信息",dataType = "String",  dataTypeClass = String.class),

            @ApiImplicitParam(name = "addressHash", value = "(不传)交易Hash地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "transactionTime", value = "(不传)交易时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "value", value = "(不传)数量", dataType = "long", dataTypeClass = long.class),
            @ApiImplicitParam(name = "currency", value = "(不传)数字货币类型 ETH,BTC,TRON", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "transactionStatus", value = "(不传)交易状态：0，提交；1，系统处理；2，区块确认；3，交易成功；4，交易失败2", dataType = "Integer", dataTypeClass = int.class),
            @ApiImplicitParam(name = "fromAddress", value = "(不传)转账钱包地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "toAddress", value = "(不传)到账地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "transactionType", value = "(不传)交易类型：0，等待；1、收款；2、转账；3，兑换；4，赚币", dataType = "Integer", dataTypeClass = int.class),
            @ApiImplicitParam(name = "creatorName", value = "(不传)创建者", dataType = "String", dataTypeClass = String.class)

    })
    @PostMapping("save")
    @Anonymous
    public AjaxResult add(@RequestBody String jsonTransaction) {
        try {
            jsonTransaction = URLDecoder.decode(jsonTransaction, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 去除 "transaction=" 前缀
        jsonTransaction = jsonTransaction.replace("transaction=", "").trim();
        //jsonTransaction = "{\"addressHash\":\"123\",\"transactionTime\":\"2024-09-14 08:48:42\",\"value\":10,\"currency\":\"TRON\",\"transactionStatus\":0, \"fromAddress\":\"TYASr5UV6HEcXatwdFQfmLVUqQQQMUxHLS\",\"toAddress\":\"TYASr5UV6HEcXatwdFQfmLVUqQQQMUxHLS\",\"transactionType\":2,\"creatorName\":\"test\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        JsonTransaction pinkoTransaction = null;
        try {
            pinkoTransaction = objectMapper.readValue(jsonTransaction, JsonTransaction.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        PinkoTransaction dto = new PinkoTransaction();
        dto.setAddressHash(pinkoTransaction.getAddressHash());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime transactionTime = LocalDateTime.parse(pinkoTransaction.getTransactionTime(), formatter);
        Date date = Date.from(transactionTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
        dto.setTransactionTime(date);

        dto.setTransactionStatus(pinkoTransaction.getTransactionStatus());
        dto.setTransactionType(pinkoTransaction.getTransactionType());
        dto.setCurrency(pinkoTransaction.getCurrency());
        dto.setCreatorName(pinkoTransaction.getCreatorName());
        dto.setFromAddress(pinkoTransaction.getFromAddress());
        dto.setToAddress(pinkoTransaction.getToAddress());
        long strvalue = pinkoTransaction.getValue();
        dto.setValue(strvalue);
        dto.setCreator(1L);
        dto.setCreateDate(new Date());
        return toAjax(pinkoTransactionService.insertPinkoTransaction(dto));
        //return toAjax(0);
    }

    /**
     * 修改Pinko交易
     */
    @PreAuthorize("@ss.hasPermi('system:transaction:edit')")
    @Log(title = "Pinko交易", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PinkoTransaction pinkoTransaction)
    {
        return toAjax(pinkoTransactionService.updatePinkoTransaction(pinkoTransaction));
    }

    /**
     * 删除Pinko交易
     */
    @PreAuthorize("@ss.hasPermi('system:transaction:remove')")
    @Log(title = "Pinko交易", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pinkoTransactionService.deletePinkoTransactionByIds(ids));
    }
}

class JsonTransaction {
    private String addressHash;
    private String transactionTime;
    private int value;
    private String currency;
    private int transactionStatus;
    private String fromAddress;
    private String toAddress;
    private int transactionType;
    private String creatorName;

    // Getters and Setters
    public String getAddressHash() {
        return addressHash;
    }

    public void setAddressHash(String addressHash) {
        this.addressHash = addressHash;
    }

    public String getTransactionTime() {
        return transactionTime;
    }

    public void setTransactionTime(String transactionTime) {
        this.transactionTime = transactionTime;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public int getTransactionStatus() {
        return transactionStatus;
    }

    public void setTransactionStatus(int transactionStatus) {
        this.transactionStatus = transactionStatus;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public int getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(int transactionType) {
        this.transactionType = transactionType;
    }

    public String getCreatorName() {
        return creatorName;
    }

    public void setCreatorName(String creatorName) {
        this.creatorName = creatorName;
    }

    @Override
    public String toString() {
        return "JsonTransaction{" +
                "addressHash='" + addressHash + '\'' +
                ", transactionTime='" + transactionTime + '\'' +
                ", value=" + value +
                ", currency='" + currency + '\'' +
                ", transactionStatus=" + transactionStatus +
                ", fromAddress='" + fromAddress + '\'' +
                ", toAddress='" + toAddress + '\'' +
                ", transactionType=" + transactionType +
                ", creatorName='" + creatorName + '\'' +
                '}';
    }
}
